package makemachine.demos.audio.microphone.capture
{
	import flash.events.*;
	import flash.media.Microphone;
	import flash.utils.ByteArray;
	
	/**
	 * Wraps a Microphone instance and stores input from it in a byte array
	 */
	public class MicrophoneInput extends EventDispatcher
	{
		public function MicrophoneInput()
		{
			super();
		}
		
		// --------------------------------------------------
		//
		// -- properties
		// 
		// --------------------------------------------------
		
		protected var initialized:Boolean;
		
		// -- buffer for storing audio data
		protected var _buffer:ByteArray;
		public function get buffer():ByteArray { return _buffer; }
		
		// -- reference to the mic
		protected var _mic:Microphone;
		public function get microphone():Microphone { return _mic; }
		
		// -- indicates whether or not recording is happening
		protected var _recording:Boolean;
		public function get recording():Boolean { return _recording; }
		
		// --------------------------------------------------
		//
		// -- public methods
		// 
		// --------------------------------------------------
		
		// -- by calling init this object will begin listening to audio input
		public function init():void 
		{
			initialized = true;
			_buffer = new ByteArray();
			_mic = Microphone.getMicrophone();
			_mic.addEventListener( SampleDataEvent.SAMPLE_DATA, onSampleData );
		}
		
		// -- sets _recording flag to true, which allows input to be stored in buffer
		public function record():void 
		{
			if( !initialized ) init();
			_recording = true;
		}	
		
		// -- stops recording
		public function stop():void 
		{
			_recording = false;
		}
		
		// -- clears the buffer and stops recording
		public function reset():void 
		{
			_recording = false;
			_buffer.clear();
		}
		
		// -- stops recording, clears the buffer and stops listening for mic input
		public function close():void
		{
			stop();
			reset();
			_mic.removeEventListener( SampleDataEvent.SAMPLE_DATA, onSampleData );
			dispatchEvent( new Event( Event.CLOSE ) );
		}
		
		// -- stores the audio data if we are recording
		// -- dispatches SampleDataEvent
		protected function onSampleData( event:SampleDataEvent ):void 
		{	
			if( recording )
			{
				var n:Number;
				while( event.data.bytesAvailable )
				{
					n = event.data.readFloat();
					_buffer.writeFloat( n );
					_buffer.writeFloat( n );
				}
			}
			dispatchEvent( event );
		}
	}
}